package ni;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * This class handles receiving a file via TCP
 */
public class TCPReceiver extends Thread{
	
	/**
	 * socket port
	 * link to the ni
	 * a boolean to close the thread
	 */
	private final int port = 16055;
	private ServerSocket sock;
	private ChatNI chatNI;
	private volatile boolean active;
	private File myFile = new File("a.txt");
	
	/**
	 * @param chatNI is a link to the chatNI
	 */
	public TCPReceiver(ChatNI chatNI) {
		try {
			this.sock = new ServerSocket(this.port);
		} catch (IOException e) {e.printStackTrace();}
		this.chatNI = chatNI;
		this.active = true;
	}
	
	/**
	 * closes the thread
	 * this.interrupt() allows to wake the thread up from the blocking call sock.accept()
	 */
	public void close() {
		this.active = false;
		this.interrupt();
	    try {
	    	if (this.sock != null){
	    		sock.close();
	    	}
		} catch (IOException e) {e.printStackTrace();}
	}
	
	/**
	 * receives a file sent via TCP
	 */
	public void run() {
		while(this.active){
			try {
				Socket client = sock.accept();
				byte[] data = new byte[(int) myFile.length()];
			    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
			    bis.read(data, 0, data.length);
			    OutputStream os = client.getOutputStream();
			    os.write(data, 0, data.length);
			    os.flush();
			    sock.close();
			} catch (SocketException e) {
				if (this.active == true) {
					e.printStackTrace();
				}
			} catch (IOException e) {e.printStackTrace();}
		}
	}
}
